﻿#include "opratchart.h"

OpratChart::OpratChart(QWidget *parent,QCustomPlot *pCustomPlot)
    : QCustomPlot()
  , mZoomMode(true)
  , mRubberBand(new QRubberBand(QRubberBand::Rectangle, pCustomPlot))
{
    line_colors<<QColor ("#fb4934")<<QColor ("#b8bb26")<<QColor ("#fabd2f")<<QColor ("#83a598")
              <<QColor ("#d3869b")<<QColor ("#8ec07c")<<QColor ("#fe8019")<<QColor ("#cc241d")
             <<QColor ("#98971a")<<QColor ("#d79921")<<QColor ("#458588")<<QColor ("#b16286")
            <<QColor ("#689d6a")<<QColor ("#d65d0e");
    gui_colors <<QColor (40,  41,  42,  255)<<QColor (80,  80,  80,  255)
              <<QColor (150, 150, 150, 255)<<QColor (40,  41,  42,  200)<<QColor (255,  255,  255,  255);

    Plot=pCustomPlot;
    pCustomPlot->clearItems();
    /* Background for the plot area */
    pCustomPlot->setBackground (gui_colors[4]);

    /* Used for higher performance (see QCustomPlot real time example) */
    pCustomPlot->setNotAntialiasedElements (QCP::aeAll);
    QFont font;
    font.setStyleStrategy (QFont::NoAntialias);
    font.setPixelSize(15);
    /* X Axis: Style */
    pCustomPlot->xAxis->grid()->setPen (QPen(gui_colors[2], 1, Qt::DotLine));
    pCustomPlot->xAxis->grid()->setSubGridPen (QPen(gui_colors[1], 1, Qt::DotLine));
    pCustomPlot->xAxis->grid()->setSubGridVisible (true);
    pCustomPlot->xAxis->grid()->setZeroLinePen(QPen(gui_colors[1]));//x轴0线颜色
    pCustomPlot->xAxis->setBasePen (QPen (gui_colors[1],2));
    pCustomPlot->xAxis->setTickPen (QPen (gui_colors[2]));
    pCustomPlot->xAxis->setSubTickPen (QPen (gui_colors[2]));
    pCustomPlot->xAxis->setUpperEnding (QCPLineEnding::esSpikeArrow);
    pCustomPlot->xAxis->setTickLabelColor (gui_colors[2]);
    pCustomPlot->xAxis->setTickLabelFont (font);
    //pCustomPlot->xAxis->setNumberFormat("g");
    //pCustomPlot->xAxis->setNumberPrecision(1);
    //pCustomPlot->xAxis->setSubTicks(true);
    //pCustomPlot->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);
    //pCustomPlot->xAxis->setLabel(tr("时间"));//轴标签

    //QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    //dateTicker->setDateTimeFormat("hh:mm:ss"); // yyyy-MM-dd hh:mm:ss
    //pCustomPlot->xAxis->setTicker(dateTicker);
    /* Y Axis */
    pCustomPlot->yAxis->grid()->setPen (QPen(gui_colors[2], 1, Qt::DotLine));
    pCustomPlot->yAxis->grid()->setSubGridPen (QPen(gui_colors[2], 1, Qt::DotLine));
    pCustomPlot->yAxis->grid()->setSubGridVisible (true);
    pCustomPlot->yAxis->grid()->setZeroLinePen(QPen(gui_colors[1]));//y轴0线颜色
    pCustomPlot->yAxis->setBasePen (QPen (gui_colors[1],2));
    pCustomPlot->yAxis->setTickPen (QPen (gui_colors[2]));
    pCustomPlot->yAxis->setSubTickPen (QPen (gui_colors[2]));
    pCustomPlot->yAxis->setUpperEnding (QCPLineEnding::esSpikeArrow);
    pCustomPlot->yAxis->setTickLabelColor (gui_colors[2]);
    pCustomPlot->yAxis->setTickLabelFont (font);
    pCustomPlot->yAxis->setLabelColor(gui_colors[2]);
    //pCustomPlot->yAxis->ticker()->setTickCount(5);
    //pCustomPlot->yAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);

    //pCustomPlot->yAxis->setLabel(tr("单位"));//轴标签

    //pCustomPlot->setInteraction (QCP::iRangeDrag, true);
    //m_film_chart->setInteraction (QCP::iRangeZoom, true);
    //pCustomPlot->setInteraction (QCP::iSelectPlottables, true);
    //pCustomPlot->setInteraction (QCP::iSelectLegend, true);
    //pCustomPlot->axisRect()->setRangeDrag (Qt::Horizontal);
    //pCustomPlot->axisRect()->setRangeZoom (Qt::Horizontal);

    /* Legend 图例设置*/
    QFont legendFont;
    legendFont.setStyleStrategy (QFont::NoAntialias);
    legendFont.setPixelSize(13);
    legendFont.setFamily("YouYuan");
    pCustomPlot->legend->setVisible (true);
    pCustomPlot->legend->setFont (legendFont);
    pCustomPlot->legend->setBrush (QColor(255,255,255,0));
    pCustomPlot->legend->setBorderPen(Qt::NoPen);
    //pCustomPlot->legend->setSelectedParts(QCPLegend::spItems);
    pCustomPlot->axisRect()->insetLayout()->setInsetAlignment (0, Qt::AlignTop|Qt::AlignLeft);

    pCustomPlot->axisRect()->addAxis(QCPAxis::atRight);
    //pCustomPlot->axisRect()->axis(QCPAxis::atRight, 0)->setPadding(50); // add some padding to have space for tags
    pCustomPlot->axisRect()->axis(QCPAxis::atRight, 1)->setPadding(80); // add some padding to have space for tags
    pCustomPlot->axisRect()->axis(QCPAxis::atRight, 1)->setTickLabelFont(font);
    pCustomPlot->axisRect()->axis(QCPAxis::atRight, 1)->setTickLabels(false);
    pCustomPlot->axisRect()->axis(QCPAxis::atRight, 1)->setTickLabelColor (gui_colors[2]);

    pCustomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom |QCP::iSelectAxes| QCP::iSelectPlottables|QCP::iMultiSelect|QCP::iSelectLegend);

    //double now = QDateTime::currentDateTime().toTime_t();
    pCustomPlot->xAxis->setRange(0, 100);
    pCustomPlot->yAxis->setRange(0, 30);

    //pCustomPlot->setOpenGl(true);//打开后关闭有问题

    //tracer=new QCPItemTracer(pCustomPlot);
    //tracerLabel=new QCPItemText(pCustomPlot);
    //m_TraserX = new myTracer(pCustomPlot, XAxisTracer);
    //m_TraserY = new myTracer(pCustomPlot, YAxisTracer);
    m_TraserD = new myTracer(pCustomPlot, DataTracer);

    connect(pCustomPlot,SIGNAL(mousePress(QMouseEvent *)),this,SLOT(mousePressEvent(QMouseEvent *)));
    connect(pCustomPlot, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(mouseMoveEvent(QMouseEvent*)));
    connect(pCustomPlot, SIGNAL(mouseRelease(QMouseEvent*)), this, SLOT(mouseReleaseEvent(QMouseEvent*)));
}

OpratChart::~OpratChart()
{
    //delete  m_TraserX;
    //delete m_TraserY;
    delete m_TraserD;
    //delete GraphIndexed;
}

void OpratChart::setZoomMode(bool mode)
{
    mZoomMode = mode;
}

void OpratChart::SetShowTracer(bool isShow)
{
    ShowTracer=true;
}

void OpratChart::AddGraphs(QString name,QColor color)
{
    Plot->addGraph();
    Plot->graph()->setName(name);
    Plot->graph()->setPen (QPen(color,2));
    Plot->graph()->setAdaptiveSampling(true);

    m_filmTag.append(new AxisTag(Plot->graph()->valueAxis()));  //插入标签
    m_filmTag.last()->setPen(Plot->graph()->pen());

}

void OpratChart::ChangeColor(int index, QColor color)
{
    qDebug()<<index;
    Plot->graph(index)->setPen (color);
    m_filmTag.at(index)->setPen(Plot->graph(index)->pen());
}

void OpratChart::RemoveGraphs(int devIndex)
{
    Plot->removeGraph(devIndex);
    delete  m_filmTag.at(devIndex);
    m_filmTag.removeAt(devIndex);
}


void OpratChart::SetLabelText(int devIndex,double value)
{
    m_filmTag.at(devIndex)->updatePosition(value);
    m_filmTag.at(devIndex)->setText(QString::number(value, 'f',2));
}

void OpratChart::SetTrance(QCPGraph *GraphIndex)
{
    GraphIndexed=GraphIndex;
    //m_TraserX->setGraph(GraphIndex);
    //m_TraserY->setGraph(GraphIndex);
    m_TraserD->setGraph(GraphIndex);
    ShowTracer=true;
}

void OpratChart::clearTrance()
{
    ShowTracer=false;
    GraphIndexed=nullptr;
    //m_TraserX->clearGraph();
    //m_TraserY->clearGraph();
    m_TraserD->clearGraph();
}

int OpratChart::GetFps()
{
    return fps;
}

void OpratChart::mousePressEvent(QMouseEvent *event)
{
    if (mZoomMode)
    {
        if (event->button() == Qt::RightButton)
        {
            mOrigin = event->pos();
            XX[0]=mOrigin.x();
            mRubberBand->setGeometry(QRect(mOrigin, QSize()));
            mRubberBand->show();
        }
    }
    QCustomPlot::mousePressEvent(event);
}

void OpratChart::mouseMoveEvent(QMouseEvent *event)
{

    if (mRubberBand->isVisible())
    {
        mRubberBand->setGeometry(QRect(mOrigin, event->pos()).normalized());
    }

    if(ShowTracer)
    {
        /*
        double x = event->pos().x();
        double y = event->pos().y();

        double x_ = Plot->xAxis->pixelToCoord(x);
        double y_ = Plot->yAxis->pixelToCoord(y);
        QString str = QString("x:%1\ny:%2\n左键可截取区域\n右键可放大区域").arg(x_)
                .arg(QString::number(y_));
        QToolTip::showText(cursor().pos(),str,Plot);
        */
        double x = Plot->xAxis->pixelToCoord(event->pos().x());
        //m_TraserX->updatePosition(x, 0);
        //m_TraserX->setText(QString::number(x, 'f', 0));

        double y = 0;
        QSharedPointer<QCPGraphDataContainer> tmpContainer;
        tmpContainer = GraphIndexed->data();
        //使用二分法快速查找所在点数据
        int low = 0, high = tmpContainer->size();
        while(high > low)
        {
            int middle = (low + high) / 2;
            if(x < tmpContainer->constBegin()->mainKey() ||
                    x > (tmpContainer->constEnd()-1)->mainKey())
                break;

            if(x == (tmpContainer->constBegin() + middle)->mainKey())
            {
                y = (tmpContainer->constBegin() + middle)->mainValue();
                break;
            }
            if(x > (tmpContainer->constBegin() + middle)->mainKey())
            {
                low = middle;
            }
            else if(x < (tmpContainer->constBegin() + middle)->mainKey())
            {
                high = middle;
            }
            if(high - low <= 1)
            {   //差值计算所在位置数据
                y = (tmpContainer->constBegin()+low)->mainValue() + ( (x - (tmpContainer->constBegin() + low)->mainKey()) *
                    ((tmpContainer->constBegin()+high)->mainValue() - (tmpContainer->constBegin()+low)->mainValue()) ) /
                    ((tmpContainer->constBegin()+high)->mainKey() - (tmpContainer->constBegin()+low)->mainKey());
                break;
            }

        }

        //m_TraserY->updatePosition(x, y);
        //m_TraserY->setText(QString::number(y, 'f', 2));
        fps=x;
        m_TraserD->updatePosition(x, y);
        m_TraserD->setText(QString("帧数:%1\n测量值:%2").arg(QString::number(x, 'f', 0))
                                               .arg(QString::number(y, 'f', 2)));
        Plot->replot(QCustomPlot::rpQueuedReplot);
    }

    QCustomPlot::mouseMoveEvent(event);
}

void OpratChart::mouseReleaseEvent(QMouseEvent *event)
{
    if (mRubberBand->isVisible())
    {
        const QRect zoomRect = mRubberBand->geometry();
        int xp1, yp1, xp2, yp2;
        zoomRect.getCoords(&xp1, &yp1, &xp2, &yp2);

        qDebug()<<xp1<<","<<yp1<<";"<<xp2<<","<<yp2;

        double x1 = Plot->xAxis->pixelToCoord(xp1);
        double x2 = Plot->xAxis->pixelToCoord(xp2);
        double y1 = Plot->yAxis->pixelToCoord(yp1);
        double y2 = Plot->yAxis->pixelToCoord(yp2);


        XX[1]=event->pos().x();
        qDebug()<<XX[0]<<","<<XX[1];
        if(XX[0]-XX[1]>0)
        {
            Plot->rescaleAxes(true);
        }
        else{
            Plot->xAxis->setRange(x1, x2);
            Plot->yAxis->setRange(y1, y2);
        }
        mRubberBand->hide();
        Plot->replot();
    }
    QCustomPlot::mouseReleaseEvent(event);
}



